<template>
  <div>
    <table border="1" width="700" style="border-collapse: collapse">
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th><input type="checkbox" v-model="isAll" /> <span>全选</span></th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in goodList" :key="index">
          <td><input type="checkbox" v-model="item.checked" :value="item.checked" @input="chenckChange($event, item.name)" /></td>
          <td>{{ item.name }}</td>
          <td>{{ item.price }}</td>
          <td>
            <button @click="changeNum(-1, item)">-</button>
            {{ item.num }}
            <button @click="changeNum(1, item)">+</button>
          </td>
          <td>{{ item.price * item.num }}</td>
          <td><button @click="changeDel(item.name)">删除</button></td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td>合计:</td>
          <td colspan="5">{{ sum }}</td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
export default {
  data () {
    return {}
  },
  computed: {
    ...mapState(['goodList']),
    isAll: {
      get () {
        return this.goodList.every((item) => item.checked === true)
      },
      set (val) {
        this.goodList.forEach((item) => {
          item.checked = val
        })
      }
    },
    arr () {
      return this.goodList.filter(item => item.checked)
    },
    sum () {
      return this.arr.reduce((sum, item) => sum + item.price * item.num, 0)
    }
  },
  methods: {
    ...mapMutations(['setNum', 'setCheck', 'setDel']),
    chenckChange (e, name) {
      this.setCheck({
        name: name,
        checked: e.target.value
      })
    },
    changeNum (num, item) {
      const newNum = item.num + num
      if (newNum < 0) return '数量不得小于零'
      this.setNum({
        name: item.name,
        num: newNum
      })
      // this.$store.commit('setNum', {
      //   name: item.name,
      //   num: newNum
      // })
    },
    changeDel (name) {
      this.setDel({
        name: name
      })
    }
  }
}
</script>

<style></style>
